package com.yy.train.ticket.train.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yy.train.ticket.train.entity.TuUserEntity;
import com.yy.train.ticket.train.service.TuUserService;
import com.yy.train.ticket.utils.JwtUtils;
import com.yy.train.ticket.utils.MD5Utils;
import com.yy.train.ticket.utils.R;
import com.yy.train.ticket.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 用户表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2023-09-25 14:36:08
 */
@RestController
@RequestMapping("tu/user")
public class TuUserController {
    @Autowired
    private TuUserService tuUserService;
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    /**
     * 列表
     */
    @RequestMapping("/login")
    public R login(@RequestBody TuUserEntity user) throws Exception {
        // 0. 判断用户名和密码不能为空
        if (StringUtils.isBlank(user.getUserName())
                || StringUtils.isBlank(user.getPassword())) {
            return R.error("用户名或密码不能为空...");
        }

        // 1. 判断用户名是否存在，如果存在就登录，如果不存在则注册
        TuUserEntity tuUserEntity = tuUserService.getOne( Wrappers.<TuUserEntity>lambdaQuery()
                .eq(TuUserEntity::getUserName, user.getUserName())
                .eq(TuUserEntity::getPassword,MD5Utils.getMD5Str(user.getPassword())));


        if (tuUserEntity!=null) {

            String jwtToken = jwtUtils.generateToken(tuUserEntity.getUserName());


            Result result =new Result();
            result.setJwt(jwtToken);
            result.setTuUserEntity(tuUserEntity);
            return R.ok(result);

        }else    {
            return R.error("用户名或密码不正确...");
        }


    }



}
